<?php
class Commquestion extends Base_Controller
{
    public function __construct()
    {
        /******待编辑******/
        $this->_page_size = 10;
        $this->_form_type = 'commq';
        $this->_list_where = array();
        $this->_action_list = array('EDIT',array('controller'=>'admin/commanswer/','function'=>'showlist','label'=>'回答'),
            array('controller'=>'admin/commquestion/','function'=>'addAudioAns','label'=>'音频'),
            array('controller'=>'admin/commsubq/','function'=>'showlist','label'=>'话题'),
            array('controller'=>'admin/commqpass/','function'=>'editqpass','label'=>'添加控制')
        );
        $this->_controller = 'admin/commquestion/';
        parent::__construct();
        $this->load->model('redis_model');
    }

    public function showList($page = 1)
    {
        $get = $this->input->get();
        if (!empty($get)){
            $where = array();
            $start = !empty($get['start'])?strtotime(trim($get['start'])):'';
            $end = !empty($get['end'])?strtotime(trim($get['end'])):'';
            $user = !empty($get['fusername'])?trim($get['fusername']):'';
            $question = !empty($get['fquestion'])?trim($get['fquestion']):'';
            if (!empty($start)) $where['q.changed >'] = $start;
            if (!empty($end)) $where['q.changed <'] = $end;
            if (!empty($user)) $where['u.userName LIKE']= '%'.$user.'%';
            if (!empty($question)) $where['q.question LIKE']= '%'.$question.'%';
            $this->_list_where = $where;
            $filter = $this->load->view('admin/form/filter/qlistfilter',array('controller'=>site_url($this->_controller),
                'start'=>$get['start'],'end'=>$get['end'],'fusername'=>$user,'fquestion'=>$question),true);
        }else{
            $filter = $this->load->view('admin/form/filter/qlistfilter',array('controller'=>site_url($this->_controller)),true);
        }
        $limit = $this->_page_size;
        $offset = ($page-1) * $limit;
        $pdata = $this->getPagination($this->_controller.'showList/');

        $res = $this->getList($offset,$limit);
        $createbtn = $this->load->view('admin/form/createbtn',array('controller'=>site_url($this->_controller)),true);

        $data = array('headers'=>$res['headers'],'list'=>$res['list'],'pagination'=>$pdata['pagination'],'createbtn'=>$createbtn,'filter'=>$filter);
        $content = $this->load->view('admin/form/list',$data,true);

        echo $this->getAdminView($content);
    }

    //重写获取list数据
    public function getList($offset = 0,$limit = 0)
    {
        $this->db->select('q.id,u.userName,q.question,q.changed')->from('comm_question as q')->join('mod_user as u','u.uid = q.uid','left');
        if (!empty($this->_list_where)) $this->db->where($this->_list_where);
        if (!empty($limit)) $this->db->limit($limit,$offset);
        $this->db->order_by('q.created','DESC');
        $data=$this->db->get()->result_array();

        $res = array('headers'=>array(),'list'=>array());
        foreach($data as $row){
            $rowdata = array();
            $rowdata['userName']=$row['userName'];
            $rowdata['question']=$row['question'];
            $rowdata['changed']=date('Y-m-d H:i:s',$row['changed']);
            $rowdata['actionlist']=$this->adminform_model->getActionList($this->_action_list,$this->_controller,$row['id'],0);
            $res['list'][]=$rowdata;
        }
        $res['headers']=array('提问者','问题','创建时间','操作');
        return $res;
    }

    public function getPagination($uri = '')
    {
        $this->db->from('comm_question as q')->join('mod_user as u','u.uid = q.uid','left');
        if (!empty($this->_list_where)) $this->db->where($this->_list_where);
        $total = $this->db->count_all_results();

        $this->load->library('pagination');
        $config['base_url'] = site_url($uri);
        $config['total_rows'] = $total;
        $config['per_page'] = $this->_page_size;
        $config['suffix'] = '?'.$_SERVER['QUERY_STRING'];
        $config['first_url'] = $config['base_url'].'1?'.$_SERVER['QUERY_STRING'];
        $config['cur_tag_open'] = '<div class="cur-page">';
        $config['cur_tag_close'] = '</div>';
        $config['use_page_numbers'] = TRUE;
        $config['num_tag_open'] = '<div class="pageitem">';
        $config['num_tag_close'] = '</div>';
        $config['prev_link'] = '上一页';
        $config['prev_tag_open'] = '<div class="pre-page">';
        $config['prev_tag_close'] = '</div>';
        $config['next_link'] = '下一页';
        $config['next_tag_open'] = '<div class="next-page">';
        $config['next_tag_close'] = '</div>';
        $config['last_link'] = '最后一页';
        $config['last_tag_open'] = '<div class="last-page">';
        $config['last_tag_close'] = '</div>';
        $config['first_link'] = '第一页';
        $config['first_tag_open'] = '<div class="first-page">';
        $config['first_tag_close'] = '</div>';
        $config['full_tag_open'] = '<div class="page-total-results">共'.$total.'条，每页'.$this->_page_size.'条</div>';

        $this->pagination->initialize($config);

        return array('total'=>$total,'pagination'=>$this->pagination->create_links());
    }

    public function update($id = 0)
    {
        $post = $this->input->post();
        if(empty($post)){
            $form = $this->updateBuildForm($id);
            $content = $this->load->view('admin/form/edit',array('controller'=>site_url($this->_controller),'form'=>$form),true);
            echo $this->getAdminView($content);
        }else{
            /******待编辑******/
            //filter post data
            $post['question'] = trim($post['question']);
            $post['changed'] = time();

            $this->_update_data = $post;
            parent::update($id);
        }
    }

    public function create()
    {
        $post = $this->input->post();
        if(empty($post)){
            $form = $this->createBuildForm();
            $content = $this->load->view('admin/form/edit',array('controller'=>site_url($this->_controller),'form'=>$form),true);
            echo $this->getAdminView($content);
        }else{
            /******待编辑******/
            //filter post data
            $post['question'] = trim($post['question']);
//            $uid = $this->_uid;
//            $user = $this->adminuser_model->getUser($uid);
//            $post['uid'] = (int)$user['commid'];
            $post['uid']=1;//一问奕答管理员
            $post['score']= round(time()/10000);
            $post['created'] = time();
            $post['changed'] = time();

            $this->_create_data = $post;
            parent::create();
        }
    }

    public function addAudioAns($qid=0)
    {
        $post = $this->input->post();
        $this->_form_type = 'comm_answer_audio';
        $this->setFormtable();
        $exist = $this->adminform_model->checkExist('comm_answer_audio','id',array('qid'=>$qid));
        if(empty($post)){
            //不存在 create
            if (empty($exist)){
                $form = $this->createBuildForm();
                $content = $this->load->view('admin/form/edit',array('controller'=>site_url($this->_controller),'form'=>$form),true);
                echo $this->getAdminView($content);
            }
            //存在 update
            else{
                $form = $this->updateBuildForm($exist['id']);
                $content = $this->load->view('admin/form/edit',array('controller'=>site_url($this->_controller),'form'=>$form),true);
                echo $this->getAdminView($content);
            }
        }else{
            //filter post data
//            $post['created'] = time();
            $dbdata = array();
            $dbdata['qid'] = (int)$qid;
            $dbdata['title'] = $post['title'];
            $voices = $this->uploadvoice('audio');
            if ($voices['code'] == 1){
                $dbdata['audio'] = implode("|",$voices['voiceurl']);
            }
            $oldimgs = $this->adminform_model->getRowData('comm_answer_audio','note',array('qid'=>(int)$qid));
            $oldimgs = $oldimgs['note'];
            $delimgs = $post['del'];
            if (!empty($delimgs)||$delimgs==='0'){
                $delimgs=explode('|',$delimgs);
                $oldimgs = explode('|',$oldimgs);
                foreach ($delimgs as $d){
                    unset($oldimgs[$d]);
                }
                $oldimgs = implode('|',$oldimgs);
            }
            $dbdata['note'] = $oldimgs;
            $imgs = $this->uploadImg('note',500);
            if ($imgs['code'] == 1){
                if (!empty($dbdata['note'])) $dbdata['note'] .= '|'.implode("|",$imgs['imgurl']);
                else $dbdata['note'] = implode("|",$imgs['imgurl']);
            }
            //不存在 create
            if (empty($exist)){
                $dbdata['created']=time();
                $dbdata['changed']=time();
                if (!isset($dbdata['note'])) $dbdata['note']='';
                $audioid = $this->adminform_model->create('comm_answer_audio',$dbdata);
                //成功创建后
                if ($audioid>0){
                    //更新问题状态
                    $data = array();
                    $data['isresponsed']=1;
                    $data['anslink']='http://wap.nldou.com/comm/audio.html?qid='.$dbdata['qid'];
                    $res = $this->db->update('comm_question',$data,'id='.$dbdata['qid']);
                    if ($res){
                        //redis更新，推送系统通知
                        $op = array('type'=>'resq','data'=>array('qid'=>$dbdata['qid']));
                        $op = igbinary_serialize($op);
                        $this->load->model('redis_model');
                        $redis = $this->redis_model->getRedisInstance();
                        $qbeans = $redis->zScore('question:beansrank',$dbdata['qid']);
                        $redis->multi()->zAdd('question:beansrank:responsed',$qbeans,$dbdata['qid'])
                            ->zRem('question:beansrank',$dbdata['qid'])->exec();
                    }
                }
            }
            //存在 update
            else{
                $dbdata['changed']=time();
                $this->adminform_model->update('comm_answer_audio',$dbdata,'id',$exist['id']);
            }
            redirect(site_url($this->_controller).'addAudioAns/'.$dbdata['qid']);
        }
    }

    public function aftercreate($id)
    {
        $res = $this->adminform_model->getRowData('comm_question','uid',array('id'=>$id));
        $this->load->model('redis_model');
        $redis = $this->redis_model->getRedisInstance();
        $redis->multi()->set('question:'.$id.'.viewsraw','')->hMSet('question:'.$id,array('id'=>$id,'uid'=>$res['uid'],'views'=>0,'follows'=>0,'beans'=>0,
            'answers'=>0,'created'=>time()))->exec();
    }

    public function delete($id){return false;}

}